const openid = getApp().globalData.openid;

Page({
    data: {
        // 左侧菜单
        menuMemo: [],
        // 右侧全部列表
        menuList: [],
        // 右侧选中列表
        rightContent: [],
        // 当前选中的菜单项
        currentIndex: 0,
        // 切换菜单项时右侧列表滚动位置置顶
        scrollTop: 0,
        // 弹窗显示加入的菜的图片
        imgUrl: "../../icon/eat.png",
        fileId: "",
        // 弹窗显示加入的菜的名字
        name: "香辛料",
        // 已选几样
        count: 0,
        // 隐藏弹窗
        shadowDisplay: "none",
        addMemoDisplay: "none",
        addCateDisplay: "none",
        addListDisplay: "none",
        imgDisplay: "block",
        // 警告提醒
        warnText: "",
        warnVisibility: "hidden",
        warnAnimation: {},
    },

    //左侧菜单的点击事件
    updatePage(e) {
        const index = e.currentTarget.dataset.index;
        const list = this.data.menuList[index];
        let rightContent;
        if (list) {
            rightContent = list;
        } else {
            rightContent = null;
        }
        this.setData({
            currentIndex: e.currentTarget.dataset.index,
            rightContent: rightContent,
            scrollTop: 0
        })
    },

    //点击加入备忘录按钮显示弹窗
    showPopWindow(e) {
        this.setData({
            shadowDisplay: "block",
            addMemoDisplay: "block",
            imgUrl: e.currentTarget.dataset.img,
            name: e.currentTarget.dataset.name,
            fileId: e.currentTarget.dataset.fileid
        });
    },

    //点击灰色透明区域取消弹窗
    cancelAdd(e) {
        this.setData({
            shadowDisplay: "none",
            addMemoDisplay: "none",
            addCateDisplay: "none",
            addListDisplay: "none",
            decreaseColor: "gray"
        })
    },

    //点击确定添加按钮 添加到备忘录
    add(e) {
        let data = this.data
        this.setData({
            count: data.count + 1
        })
        let newItem = {
            imgUrl: data.imgUrl,
            name: data.name,
            fileId: data.fileId
        };
        let menuChoosed = wx.getStorageSync('menuChoosed');
        if (!menuChoosed) {
            menuChoosed = new Array();
        }
        menuChoosed.push(newItem);
        wx.setStorageSync('menuChoosed', menuChoosed);

        // 显示添加成功动画
        this.setData({
            imgDisplay: "block"
        })
        let animation = wx.createAnimation({
            delay: 0,
            duration: 1000,
            timingFunction: "ease"
        })
        animation.translate(-20, 100).scale(0.01).step();
        this.setData({
            closeAnimation: animation.export()
        });

        // 关闭弹窗
        let that = this;
        setTimeout(function () {
            animation.translate(0).scale(1).step();
            that.setData({
                closeAnimation: animation.export(),
                imgDisplay: "none",
                decreaseColor: "gray"
            })
            that.cancelAdd();
        }, 1200);
    },

    //添加自定义菜单项
    addCate(e) {
        this.setData({
            shadowDisplay: "block",
            addCateDisplay: "block"
        })
    },
    onUpdateMemo(e) {
        let temp = this.data.menuMemo;
        if (!temp) {
            temp = [];
        }
        temp.push(e.detail);
        this.setData({
            menuMemo: temp
        });
        wx.setStorageSync('menuMemo', temp);
    },

    //添加自定义菜品
    addList(e) {
        this.setData({
            shadowDisplay: "block",
            addListDisplay: "block"
        })
    },
    onUpdateList(e) {
        let index = this.data.currentIndex;
        let temp = this.data.menuList[index];
        if (!temp) {
            temp = [];
        }
        temp.push(e.detail);
        this.setData({
            ["menuList[" + index + "]"]: temp,
            rightContent: temp
        });
        wx.setStorageSync('menuList', this.data.menuList);
    },

    // 点击中间弹窗的确认添加关闭弹窗
    oncloseHandler(e) {
        let that = this;
        if (e.detail) {
            setTimeout(function () {
                that.cancelAdd();
            }, 1800);
        }
    },

    //添加自定义时没有输入名称显示警告弹窗
    onwarnHandler() {
        this.showWarning("还没有输入名称！");
    },

    // 显示警告弹窗
    showWarning(text) {
        this.setData({
            warnText: text,
            warnVisibility: "visible"
        });
        let animation = wx.createAnimation({
            delay: 0,
            duration: 800,
            timingFunction: "ease"
        });
        animation.opacity(1).step();
        this.setData({
            warnAnimation: animation.export()
        });
        let that = this;
        setTimeout(function () {
            animation.opacity(0).step();
            that.setData({
                warnAnimation: animation.export()
            })
        }, 2300);
        setTimeout(function () {
            that.setData({
                warnVisibility: "hidden"
            })
        }, 3100);
    },

    //长按删除menuMemo项
    deleteMemoItem(e) {
        if (e.currentTarget.dataset.index <= 2) {
            wx.showModal({
                title: "删除提示",
                content: "前三项荤素汤为默认项不能删除！"
            })
        } else {
            wx.showModal({
                title: "删除提示",
                content: '确定要删除“' + e.currentTarget.dataset.name + '”吗? 您保存的该项所有数据都将丢失！',
                success: res => {
                    if (res.confirm) {
                        let menuMemo = this.data.menuMemo;
                        let menuList = this.data.menuList;
                        //从数组中删去这一项并保存到缓存
                        let deleteMemo = menuMemo.splice(e.currentTarget.dataset.index, 1);
                        let deleteList = menuList.splice(e.currentTarget.dataset.index, 1);
                        this.setData({
                            menuMemo: menuMemo,
                            menuList: menuList
                        });
                        wx.setStorageSync('menuMemo', menuMemo);
                        wx.setStorageSync('menuList', menuList);

                        //删除云储存中该项对应的右侧列表中用户自定义的图片
                        let fileList = [];
                        if (deleteList[0]) {
                            for (let i = 0; i < deleteList[0].length; i++) {
                                if (deleteList[0][i].fileId.indexOf("userImages") >= 0) {
                                    fileList.push(deleteList[0][i].fileId);
                                }
                            }
                            wx.cloud.deleteFile({
                                fileList: fileList,
                                success: res => {
                                    console.log("删除" + deleteMemo[0] + "中用户自定义的全部图片成功");
                                },
                                fail: err => {
                                    console.log("删除用户自定义图片失败" + err);
                                }
                            });
                        }

                        //如果删除的是当前正在查看的种类，就显示上一个种类
                        if (this.data.currentIndex == e.currentTarget.dataset.index) {
                            let menuListItem = this.data.menuList[this.data.currentIndex - 1];
                            if (!menuListItem) {
                                menuListItem = {}
                            }
                            this.setData({
                                currentIndex: this.data.currentIndex - 1,
                                rightContent: menuListItem
                            });
                        }
                        wx.showToast({
                            title: '删除成功',
                        });
                    }
                }
            })
        }
    },

    //长按删除menuList项
    deleteListItem(e) {
        wx.showModal({
            title: "删除提示",
            content: '确定要删除“' + e.currentTarget.dataset.name + '”吗?',
            success: res => {
                if (res.confirm) {
                    let menuList = this.data.menuList;
                    //从数组中删去这一项并保存到缓存 
                    let deleteItem = menuList[this.data.currentIndex].splice(e.currentTarget.dataset.index, 1);
                    this.setData({
                        menuList: menuList,
                        rightContent: menuList[this.data.currentIndex]
                    });
                    wx.setStorageSync('menuList', menuList);
                    wx.showToast({
                        title: '删除成功',
                    });

                    //如果删除的是用户自定义数据就删除云储存中对应的图片
                    if (deleteItem[0].fileId.indexOf("userImages") >= 0) {
                        wx.cloud.deleteFile({
                            fileList: [deleteItem[0].fileId],
                            success: res => {
                                console.log("删除云图片成功");
                            },
                            fail: err => {
                                console.log("删除云图片失败" + err);
                            }
                        });
                    }
                }
            }
        })
    },

    //加载初始数据
    onLoad: function (options) {
        let menuMemoStorage = wx.getStorageSync('menuMemo');
        let menuListStorage = wx.getStorageSync('menuList');
        var that = this;

        //当本地缓存存在时从本地缓存加载数据,不存在时从云端获取个人数据保存在本地缓存
        if (menuMemoStorage) {
            this.setData({
                menuMemo: menuMemoStorage
            });
        } else {
            wx.cloud.database().collection("menuMemo").doc(openid).get({
                //如果云端储存了用户的个人数据就加载个人数据
                success: res => {
                    wx.setStorageSync('menuMemo', res.data.menuMemo);
                    that.setData({
                        menuMemo: res.data.menuMemo
                    });
                },
                //如果没有储存就加载默认初始数据
                fail: err => {
                    that.setData({
                        menuMemo: wx.getStorageSync('defaultMenuMemo')
                    })
                    wx.setStorageSync('menuMemo', wx.getStorageSync('defaultMenuMemo'))
                }
            });

        }

        if (menuListStorage) {
            this.setData({
                menuList: menuListStorage,
                rightContent: menuListStorage[0]
            });
        } else {
            wx.cloud.database().collection("menuList").doc(openid).get({
                //如果云端储存了用户的个人数据就加载个人数据
                success: res => {
                    let menuList = res.data.menuList;
                    for (let i = 0; i < menuList.length; i++) {
                        if (menuList[i]) {
                            for (let j = 0; j < menuList[i].length; j++) { //这里可以先只加载第一项的图片数据来节省流量，
                                wx.cloud.downloadFile({ //甚至只加载第一页的前几项，后面的通过下拉刷新加载，后面改一下
                                    fileID: menuList[i][j].fileId,
                                    success: res => {
                                        menuList[i][j].imgUrl = res.tempFilePath;
                                        wx.setStorageSync('menuList', menuList);
                                        that.setData({
                                            menuList: menuList,
                                            rightContent: menuList[0]
                                        });
                                    }
                                })
                            }
                        }
                    }
                },
                //如果没有储存就加载默认初始数据
                fail: err => {
                    this.setData({
                        menuList: wx.getStorageSync('defaultMenuList'),
                        rightContent: wx.getStorageSync('defaultMenuList')[0]
                    });
                    wx.setStorageSync('menuList', wx.getStorageSync('defaultMenuList'));
                }
            });
        }
    },

    //页面显示时的操作
    onShow: function () {
        //记录本次打开页面时的缓存，用来判断是否有过更改
        this.setData({
            oldMenuMemoStorage: wx.getStorageSync('menuMemo'),
            oldMenuListStorage: wx.getStorageSync('menuList'),
            oldMenuChoosedStorage: wx.getStorageSync('menuChoosed')
        });

        //刷新已选count数
        let menuChoosed = wx.getStorageSync('menuChoosed');
        if (menuChoosed) {
            this.setData({
                count: menuChoosed.length,
            });
        } else {
            wx.cloud.database().collection("menuChoosed").doc(openid).get({
                success: res => {
                    wx.setStorageSync('menuChoosed', res.data.menuChoosed);
                    that.setData({
                        count: res.data.menuChoosed.length
                    });
                },
                fail: err => {
                    console.log("没有云端menuChoosed数据");
                }
            })
        }
    },

    //当有数据变化时保存数据到云服务器
    onHide: function () {
        const menuMemoDB = wx.cloud.database().collection("menuMemo");
        const menuListDB = wx.cloud.database().collection("menuList");
        const menuChoosedDB = wx.cloud.database().collection("menuChoosed");
        const menuMemo = wx.getStorageSync('menuMemo');
        const menuList = wx.getStorageSync('menuList');
        const menuChoosed = wx.getStorageSync('menuChoosed');
        //保存左侧菜单
        if (JSON.stringify(menuMemo) != JSON.stringify(this.data.oldMenuMemoStorage)) {
            menuMemoDB.where({
                _id: openid
            }).get().then(res => {
                if (res.data.length == 0) { //如果云端不存在该用户的menuMemo数据就添加
                    menuMemoDB.add({
                        data: {
                            _id: openid,
                            menuMemo: menuMemo
                        },
                        success: res => {
                            console.log("创建menuMemo数据表成功");
                        },
                        fail: err => {
                            console.log("创建menuMemo数据表出错" + err);
                        }
                    });
                } else { //如果云端存在该用户的menuMemo数据就更新
                    menuMemoDB.doc(openid).update({
                        data: {
                            menuMemo: menuMemo
                        },
                        success: res => {
                            console.log("更新menuMemo数据表成功");
                        },
                        fail: err => {
                            console.log("更新menuMemo数据表出错" + err);
                        }
                    })
                }
            })
        }
        //保存右侧列表
        if (JSON.stringify(menuList) != JSON.stringify(this.data.oldMenuListStorage)) {
            menuListDB.where({
                _id: openid
            }).get().then(res => {
                if (res.data.length == 0) {
                    menuListDB.add({
                        data: {
                            _id: openid,
                            menuList: menuList
                        },
                        success: res => {
                            console.log("创建menuList数据表成功");
                        },
                        fail: err => {
                            console.log("创建menuList数据表出错" + err);
                        }
                    });
                } else {
                    menuListDB.doc(openid).update({
                        data: {
                            menuList: menuList
                        },
                        success: res => {
                            console.log("更新menuList数据表成功");
                        },
                        fail: err => {
                            console.log("更新menuList数据表出错" + err);
                        }
                    })
                }
            })
        }
        //保存加入备忘录的材料
        if (JSON.stringify(menuChoosed) != JSON.stringify(this.data.oldMenuChoosedStorage)) {
            menuChoosedDB.where({
                _id: openid
            }).get().then(res => {
                //如果云端储存的列表为空就直接add添加
                if (res.data.length == 0) {
                    menuChoosedDB.add({
                        data: {
                            _id: openid,
                            menuChoosed: menuChoosed
                        },
                        success: res => {
                            console.log("创建menuChoosed数据表成功");
                        },
                        fail: err => {
                            console.log("创建menuChoosed数据表出错" + err);
                        }
                    });
                }
                //云端储存的列表不为空就更新
                else {
                    menuChoosedDB.doc(openid).update({
                        data: {
                            menuChoosed: menuChoosed
                        },
                        success: res => {
                            console.log("更新menuChoosed数据表成功");
                        },
                        fail: err => {
                            console.log("更新menuChoosed数据表出错" + err);
                        }
                    })
                }
            })
        }
    }
})